package com.gps.gate;


import com.gps.common.model.Device;
import com.gps.common.model.Position;
import com.gps.gate.database.ActiveDevice;
import com.gps.gate.database.ConnectionManager;
import io.netty.channel.Channel;
import io.netty.channel.socket.DatagramChannel;
import org.apache.commons.lang3.StringUtils;

import java.net.SocketAddress;
import java.util.Collection;

public abstract class BaseProtocolDecoder extends ExtendedObjectDecoder {

    protected ConnectionManager connectionManager;

    private final Protocol protocol;

    public BaseProtocolDecoder(Protocol protocol) {
        this.protocol = protocol;
        connectionManager = GpsGateContext.getApplicationContext().getBean(ConnectionManager.class);
    }

    public String getProtocolName() {
        return protocol.getName();
    }

    public ActiveDevice getDeviceSession(Channel channel, SocketAddress remoteAddress, String imei) {
        if (channel == null || imei == null || StringUtils.isEmpty(imei)) {
            return null;
        }
        ActiveDevice deviceSession = connectionManager.getActiveDevice(channel);
        if (deviceSession != null && deviceSession.getImei().equalsIgnoreCase(imei)) {
            return deviceSession;
        }
        deviceSession = connectionManager.addActiveDevice(imei, protocol, channel, remoteAddress);
        return deviceSession;
    }

    @Override
    protected void onMessageEvent(
            Channel channel, SocketAddress remoteAddress, Object originalMessage, Object decodedMessage) {
        Position position = null;
        if (decodedMessage != null) {
            if (decodedMessage instanceof Position) {
                position = (Position) decodedMessage;
            } else if (decodedMessage instanceof Collection) {
                Collection positions = (Collection) decodedMessage;
                if (!positions.isEmpty()) {
                    position = (Position) positions.iterator().next();
                }
            }
        }
        if (position != null) {
//            if (channel instanceof DatagramChannel) {
                connectionManager.updateDevice(position.getImei(), Device.STATUS_ONLINE);
//            }
//        } else {
        }
    }

    @Override
    protected Object handleEmptyMessage(Channel channel, SocketAddress remoteAddress, Object msg) {
        return null;
    }

}
